package liuds.music;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import liuds.music.adapter.MusicAdapter;
import liuds.music.model.MediaService;
import liuds.music.utils.MusicUtils;
import liuds.music.utils.Utils;


/**
 * Created by Administrator on 2018/5/2.
 */

@SuppressLint("ValidFragment")
public class MusicFragment extends BaseFragment implements MusicAdapter.OnMusicItemClickListener {

    private RecyclerView musicListView;
    public MusicAdapter musicAdapter;

    private MainActivity mainActivity;

    private PopupWindow itemMenuWindow;
    private View itemMenuView;

    private int currentClickIndex = -1;

    @SuppressLint("ValidFragment")
    public MusicFragment(String title) {
        super(title);
    }

    @Override
    protected int getLayoutResouceId() {
        return R.layout.fragment_music;
    }

    @Override
    protected void initView(Bundle state) {
        mainActivity = (MainActivity) getActivity();

        musicListView = findViewById(R.id.musicListView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        musicListView.setLayoutManager(layoutManager);

        initItemMenuWindow();
    }


    @Override
    protected void loadData(OnLoadDataListener listener) {
//        MediaScannerConnection.scanFile(getActivity(), new String[]{Environment
//                .getExternalStorageDirectory().getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
//            @Override
//            public void onScanCompleted(String s, Uri uri) {
//            }
//        });
        if(MusicUtils.getPlayMusicList().size() <= 0){
            listener.onLoadError("无本地音乐");
        }else{
            if(musicAdapter == null){
                musicAdapter = new MusicAdapter(getContext(), MusicUtils.getLocalMusic());
                musicAdapter.setOnMusicItemClick(this);
                musicListView.setAdapter(musicAdapter);
            }else{
                musicAdapter.notifyDataSetChanged();
            }
            musicAdapter.setCurrentPlayIndex(MusicUtils.getPlayIndex());
        }
        listener.onLoadSuccess();

    }

    @Override
    public void onMusicItemClick(View v) {
        int position = musicListView.getChildAdapterPosition(v);
        mainActivity.playMusic(musicAdapter.music.get(position).getId());
    }

    private void initItemMenuWindow() {
        itemMenuView = LayoutInflater.from(getActivity()).inflate(R.layout.menu_item_window,null);
        LinearLayout handleView = itemMenuView.findViewById(R.id.handleView);
        for(int i =0;i<handleView.getChildCount();i++){
            handleView.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.play:
                            mainActivity.playMusic(musicAdapter.music.get(currentClickIndex).getId());
                            break;
                        case R.id.share:
                            App.share(getActivity(),musicAdapter.music.get(currentClickIndex).getTitle());
                            break;
                        case R.id.collect:
                            Utils.toast("收藏");
                            break;
                        case R.id.details:
                            Utils.toast("详情");
                            break;
                        case R.id.del:
                            Utils.toast("删除");
                            break;
                    }
                    itemMenuWindow.dismiss();
                }
            });
        }

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        itemMenuView.measure(w, h);

        int windowHeight = itemMenuView.getMeasuredHeight()>(App.screenHeight/2)?App.screenHeight/2:itemMenuView.getMeasuredHeight();
        itemMenuWindow = new PopupWindow(itemMenuView,App.screenWidth,windowHeight);
        itemMenuWindow.setFocusable(true);
        itemMenuWindow.setOutsideTouchable(true);
        itemMenuWindow.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.menu_item_window_bg));
        itemMenuWindow.setAnimationStyle(R.style.itemMenuOpenAnim);

        itemMenuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ValueAnimator anim = ValueAnimator.ofFloat(0.4f,1f);
                anim.setDuration(300);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float currentValue = (float) animation.getAnimatedValue();
                        backgroundAlpha(currentValue);
                    }
                });
                anim.start();
            }
        });
    }

    @Override
    public void onMusicItemMenuClick(int position) {
        this.currentClickIndex = position;
        TextView title = itemMenuView.findViewById(R.id.title);
        title.setText("歌曲: "+musicAdapter.music.get(position).getTitle());

        itemMenuWindow.showAtLocation(rootView, Gravity.BOTTOM,0,0);
        ValueAnimator anim = ValueAnimator.ofFloat(1f,0.4f);
        anim.setDuration(300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float currentValue = (float) animation.getAnimatedValue();
                backgroundAlpha(currentValue);
            }
        });
        anim.start();
    }

    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = f;
        getActivity().getWindow().setAttributes(lp);

    }
}
